import { TestConfig } from '../common/testConfig.js';
import { getApiData } from '../../network/communicationConverter.js';
import { getCommodityDataV2, getCommodityData, getCommodityDetailInfo, getCommoditySpecList } from '../../network/api.js';
import { TestSimulateData } from '../testMgr/testSimulateData.js';
import { CommunicationPageData, ApiReturnStruct, NetworkParser } from '../../network/communicationConverter.js';
import { Commodity } from '../commodity/commodity.js';
import { Engine } from '../engine.js';
import { Util } from '../../utils/util.js';
import { InventoryUiAction } from './inventoryUiAction.js';
import { SubCommodity } from '../commodity/subCommodity.js';



export class CommodityUiAction {

    /// 获取商品规格列表 (无库存信息)
    async getCommoditySpecList(    
        pageInfo,
        filter = null) {
            console.log('getCommoditySpecList filter:', filter);
        if (TestConfig.commodityDataTest) {
            // 模拟延时
            await new Promise(resolve => setTimeout(resolve, 1000));

            /// 模拟数据
            const testSimulateData = new TestSimulateData();

            let simData = new CommunicationPageData();
            simData.dataList = testSimulateData.createSimSubCommodityData();
            simData.pageInfo.total = 100;

            let ret = new ApiReturnStruct();
            ret.data = simData;
            ret.resErr = null;
            return ret;

        } else {
            const apiData = await getApiData(
                SubCommodity.fromJson,
                Engine.profile.org.orgId,
                pageInfo,
                getCommoditySpecList,
                filter,
            );

            return apiData;
        }
    }
    ///  获取商品所有信息
    async getCommodityList(
        pageInfo,
        isV2Version = true,
        filter = null) {
        if (TestConfig.commodityDataTest) {

            // 模拟延时（例如：500毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));

            /// 模拟数据
            const testSimulateData = new TestSimulateData();

            /// 模拟数据

            let simData = new CommunicationPageData();
            simData.dataList = testSimulateData.createSimCommodityData();
            simData.pageInfo.total = 100//simData.dataList.length;


            let ret = new ApiReturnStruct();

            ret.data = simData;
            ret.resErr = null;
            return ret;


        } else {
            let api = isV2Version ? getCommodityDataV2 : getCommodityData;
            const apiData = await getApiData(Commodity.fromJson, Engine.profile.org.orgId, pageInfo, api, filter);

            return apiData;
        }
    }

    // 获取商品详情
    // 返回commodity
    async getCommodityDetailInfo(commodityId) {
        if (TestConfig.commodityDataTest) {
            // 模拟延时（例如：500毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));
            /// 模拟数据
            const testSimulateData = new TestSimulateData();
            return testSimulateData.createSimCommodityData()[0];


        } else {
            let res = await getCommodityDetailInfo(commodityId, Engine.profile.org.orgId);

            // 解析数据，利用 NetworkParser 解析分页数据
            const apiResult = NetworkParser.parseNetworkResult(res, Commodity.fromJson);



            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null &&
                    typeof apiResult.resErr === 'string') {
                    Util.showToast(apiResult.resErr);
                }

                return null;
            }
        }
    }


    /// 显示commodityDetail 页面 
    async showCommodityDetailPage(commodity) {
        let updateCommodity = null; //Commodity?

        let wareHouseList = [];

        if (Engine.getOrgSettings().enableCommodityInventoryAdjustSimpleMode) {
            // 简化模式获取仓库信息
            let uiAction = new InventoryUiAction();

            const [detailResult, warehousesResult] = await Promise.all([
                this.getCommodityDetailInfo(commodity.id), // 修正拼写
                uiAction.getWarehouseList({})
            ]);

            updateCommodity = detailResult;
            wareHouseList = warehousesResult || [];
        } else {
            updateCommodity = await this.getCommodityDetailInfo(commodity.id);
        }


        if (updateCommodity != null) {
            let commodityParam = updateCommodity.toCopyJson();
            let warehouseParm = wareHouseList.map(wh => wh.toCopyJson());

            // 传参commodityParam 和 warehouseParm
            let item = {
                commodityParam: JSON.stringify(commodityParam),
                warehouseParm: JSON.stringify(warehouseParm)
            };
            uni.navigateTo({ url: `/pages/v2views/commodity/commodityDetailPage?&commodity=${encodeURIComponent(item.commodityParam)}&warehouses=${encodeURIComponent(item.warehouseParm)}` });
        } else {
            Util.showToast("商品信息获取失败");
            return null;
        }
    }
}